package vn.gq.cd.adutils;

import java.util.Random;
import android.content.Context;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import com.inmobi.androidsdk.IMAdListener;
import com.inmobi.androidsdk.IMAdRequest;
import com.inmobi.androidsdk.IMAdRequest.ErrorCode;
import com.inmobi.androidsdk.IMAdView;

public class IMAdHelper implements IMAdListener {
	
	public static final int DELAY_TIME_FAILED;
	public static final int DELAY_TIME_RELOAD;
	public static final String DEFAULT_AD_ID;
	
	private IMAdView mIMAdview;
	private Random mRandom = new Random();
	
	static {
		DELAY_TIME_FAILED = 30000;
		DELAY_TIME_RELOAD = 60000;
		DEFAULT_AD_ID = "a15155cbc7cf165";
	}
	
	public IMAdHelper(Context context, IMAdView ad) {
		ad.setIMAdListener(this);
		mIMAdview = ad;
	}
	
	public void loadAd() {
		if (mIMAdview != null) {
			IMAdRequest request = new IMAdRequest();
			mIMAdview.setIMAdRequest(request);
			mIMAdview.loadNewAd(request);
		}
	}
	
	public Runnable loadAdRun = new Runnable() {
		
		@Override
		public void run() {
			if (mIMAdview != null) {
				IMAdRequest request = new IMAdRequest();
				mIMAdview.loadNewAd(request);
			}
		}
	};
	
	public void onDestroy() {
		if (mIMAdview != null) {
			mIMAdview.destroy();
		}
	}
	
	public void onStop() {
		if (mIMAdview != null) {
			mIMAdview.stopLoading();
		}
	}
	
	@Override
	public void onAdRequestCompleted(IMAdView ad) {
		
		Log.e(getClass().getSimpleName(), "onAdRequestCompleted");
		
		ScaleAnimation zoomIn = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, 
				Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
		zoomIn.setDuration(500);
		float distance = mIMAdview.getHeight();
		TranslateAnimation slideDown = new TranslateAnimation(0, 0, -distance, 0);
		slideDown.setDuration(500);
		int idx = mRandom.nextInt(2);
		if (idx == 0)
			mIMAdview.startAnimation(zoomIn);
		else
			mIMAdview.startAnimation(slideDown);
		mIMAdview.stopLoading();
		mIMAdview.removeCallbacks(loadAdRun);
		mIMAdview.postDelayed(loadAdRun, DELAY_TIME_RELOAD);
	}

	@Override
	public void onAdRequestFailed(IMAdView ad, ErrorCode e) {
		Log.e(getClass().getSimpleName(), "onAdRequestFailed");
		mIMAdview.stopLoading();
		mIMAdview.removeCallbacks(loadAdRun);
		mIMAdview.postDelayed(loadAdRun, DELAY_TIME_FAILED);
	}

	@Override
	public void onDismissAdScreen(IMAdView ad) {
		
	}

	@Override
	public void onLeaveApplication(IMAdView ad) {
		
	}

	@Override
	public void onShowAdScreen(IMAdView ad) {
		Log.e(getClass().getSimpleName(), "onShowAdScreen");
	}
	
	
}
